#include <iostream>
#include <thread>
using namespace std;
class singleton{
public:
 //懒汉模式会存在线程安全问题，但是不会有内存的浪费
 //饿汉模式不会有线程安全问题，但是会有内存泄漏问题
   static singleton* getInstance(){
        if(!_ps){
            //懒汉模式，用到了才创建
            _ps=new singleton();
                
        cout<<"getInstance"<<endl;
        }
        return _ps;
    }
    singleton(const singleton& rhs)=delete;
    singleton& operator=(const singleton& rhs)=delete;

    
    class autorelease{
    public:
        ~autorelease(){
            cout<<"~autorelease"<<endl;
            if(_ps){
                delete  _ps;
                _ps=nullptr;
            }
        }
};
private:
singleton(){
    cout<<"singleton"<<endl;
}
~singleton(){
    cout<<"~singleton"<<endl;
}
    static singleton* _ps;
    static autorelease _ar;
};
    //饿汉模式,直接就创建一个对象出来
    singleton* singleton::_ps=nullptr;
    singleton:: autorelease singleton ::_ar;
    void test2(void);
    void test(){
        thread t1(test2);
        thread t2(test2);
        thread t3(test2);
        thread t4(test2);
        thread t5(test2);
    
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();
    }
void test2(){
    for(int i=0;i<10;i++){
        singleton::getInstance();
    }
}
    int main(int argc, char * argv[]){
        test();

        return 0;
}

